<script setup>
import { onMounted, ref } from 'vue'
import Tinymce from '@jsdawn/vue3-tinymce'
import ImageDialog from '@/components/imageDialog.vue'
import { getImgUrl } from '@/api/request'

const props = defineProps({
  modelValue: String,
})
const emits = defineEmits(['update:modelValue'])

let fontSizes = []
for (let i=12; i<=18; i++) {
  fontSizes.push(i)
}
for (let i=20; i<=30; i+=2) {
  fontSizes.push(i)
}
for (let i=32; i<=48; i+=4) {
  fontSizes.push(i)
}

const fullscreen = ref(false)

const tinymceSettings = {
  height: 400,
  toolbar:
    'undo redo | fullscreen | formatselect alignleft aligncenter alignright alignjustify | link unlink | numlist bullist | image media table | fontsizeselect forecolor backcolor | bold italic underline strikethrough | indent outdent | removeformat |',
  toolbar_drawer: 'sliding',
  // quickbars_selection_toolbar:
  //   'removeformat | bold italic underline strikethrough | fontsizeselect forecolor backcolor',
  plugins: 'link image media table lists fullscreen',
  fontsize_formats: fontSizes.map(s => `${s}px`).join(' '),
  default_link_target: '_blank',
  link_title: false,
  nonbreaking_force_tab: true,
  // 以中文简体为例
  language: 'zh_CN',
  language_url: 'https://unpkg.com/@jsdawn/vue3-tinymce@1.1.6/dist/tinymce/langs/zh_CN.js',

  // 图片粘贴
  paste_data_images: true,

  init_instance_callback: (editor) => {
    // console.log('init_instance_callback', editor)
    editor.on('FullscreenStateChanged', e => {
      fullscreen.value = e.state
    })
  }
}

const mceid = ref()
const imageList = ref([])

function imgChange() {
  if (imageList.value.length > 0) {
    window.tinymce.get(mceid.value.id).insertContent(`<img src="${getImgUrl(imageList.value[0])}">`)
  }
}
</script>

<template>
  <div class="mce-body">
    <image-dialog
      :imageList="imageList"
      :max="1"
      @change="imgChange"
      :showList="false"
      :class="{uploadBtn:true,fullscreen:fullscreen}"
    />

    <Tinymce
      ref="mceid"
      v-model="modelValue"
      :setting="tinymceSettings"
      @change="emits('update:modelValue', props.modelValue)"
    />
  </div>
</template>

<style scoped>
.mce-body {
  position: relative;
}
.uploadBtn {
  position: absolute;
  z-index: 1201;
  top: 3px;
  right: 5px;
}
.uploadBtn.fullscreen {
  position: fixed;
}
</style>